<?php

/**
 * PasswordForm class
 *
 * @author Julot <andy.julot@gmail.com>
 * @since Monday, July 25, 2011. 07:43 PM
 */
class PasswordForm extends CFormModel {

	public $oldPassword;
	public $newPassword;
	public $confirmPassword;

	/**
	 * Declares the validation rules.
	 */
	public function rules() {
		return array(
			array(
				'oldPassword, newPassword, confirmPassword',
				'required',
			),
			array(
				'oldPassword',
				'validateOldPassword',
			),
			array(
				'newPassword',
				'compare',
				'compareAttribute'=>'confirmPassword',
			),
		);
	}

	public function validateOldPassword($attribute, $params) {
		$user = $this->loadUser();
		if (!$user->validatePassword($this->{$attribute})) {
			$s = $this->getAttributeLabel($attribute) . " salah.";
			$this->addError($attribute, $s);
		}
	}

	/**
	 * Returns the data model.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadUser() {
		$model = User::model()->findByPk(Yii::app()->user->id);
		if ($model === null) {
			$message = 'The requested page does not exist.';
			throw new CHttpException(404, $message);
		}
		return $model;
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'oldPassword'=>'Password Lama',
			'newPassword'=>'Password Baru',
			'confirmPassword'=>'Konfirmasi Password',
		);
	}

}
